package org.example.memora.service.serviceImpl;

import cn.hutool.core.bean.BeanUtil;
import com.aliyun.oss.model.GenerateVodPlaylistRequest;
import org.springframework.data.domain.Page;
import org.example.memora.DTO.CommentSaveDTO;
import org.example.memora.DTO.UserRedisDTO;
import org.example.memora.common.result.PageResult;
import org.example.memora.common.result.Result;
import org.example.memora.common.utils.UserHolder;
import org.example.memora.entity.Comment;
import org.example.memora.Repository.CommentRepository;
import org.example.memora.entity.PostCommentStat;
import org.example.memora.entity.User;
import org.example.memora.mapper.PostCommentStatMapper;
import org.example.memora.mapper.PostMapper;
import org.example.memora.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.example.memora.common.constant.CommentConstants;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.mongodb.core.query.Update;
import org.bson.types.ObjectId;


import java.time.Instant;
import java.util.List;
import java.util.Optional;

import static org.example.memora.common.constant.CommentConstants.VISIBLE;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private final CommentRepository commentRepository;
    @Autowired
    private PostCommentStatMapper postCommentStatMapper;
    @Autowired
    private PostMapper postMapper;
    public CommentServiceImpl(CommentRepository commentRepository) {
        this.commentRepository = commentRepository;
    }
    @Autowired
    private  MongoTemplate mongoTemplate;

    @Override
    public Result<?> incrementReplyNumById(String commentId) {
        Query query = new Query(Criteria.where("_id").is(commentId));
        Update update = new Update().inc("reply_num", 1);
        mongoTemplate.updateFirst(query, update, Comment.class);
        return Result.success();
    }
    @Override
    public Result<?> incrementReplyNumById(String commentId, String articleId) {
        // 构造联合查询条件
        Query query = new Query(Criteria.where("_id").is(commentId).and("article_id").is(articleId));

        // 检查是否存在该评论
        boolean exists = mongoTemplate.exists(query, Comment.class);
        if (!exists) {
            return Result.error("指定评论不存在或不属于该文章");
        }

        // 更新 reply_num 字段：自增 1
        Update update = new Update().inc("reply_num", 1);
        mongoTemplate.updateFirst(query, update, Comment.class);
        return Result.success();
    }


    @Transactional
    @Override
    public Result<?> save(CommentSaveDTO commentSaveDTO) {
        UserRedisDTO userRedisDTO= (UserHolder.getUser());

        if(userRedisDTO==null){
            return Result.error("未登录账号，请先登录");
        }
        String userId=String.valueOf(userRedisDTO.getUserId());
        Comment comment=new Comment();
        comment.setUserId(userId);
        //TODO:将前端传的昵称换为直接从后端获取
        BeanUtil.copyProperties(commentSaveDTO,comment);
        comment.setArticleId(String.valueOf(commentSaveDTO.getArticleId()));
        Instant now = Instant.now();
        comment.setCreatedAt(now);
        comment.setLikeNum(0);
        comment.setReplyNum(0);
        comment.setState(VISIBLE);
        comment.setNickname(userRedisDTO.getNickname());
        if(commentSaveDTO.getParentId()==null){
            return Result.error("ParentId为空");
        }
        if (!"0".equals(commentSaveDTO.getParentId())) {
            try {
                // 直接使用 String 查询，匹配实体中的 String id
                Query query = new Query(Criteria.where("_id").is(commentSaveDTO.getParentId()));
                Comment parent = mongoTemplate.findOne(query, Comment.class);
                if (parent == null) {
                    return Result.error("上一级评论不存在");
                }
            } catch (Exception e) {
                return Result.error("parentId 查询失败：" + e.getMessage());
            }
        }


        Comment comment1=commentRepository.save(comment);
        if(comment1.getArticleId().isEmpty()){
            return Result.error("插入错误，文章不存在");
        }
        PostCommentStat postCommentStat=postCommentStatMapper.selectByPrimaryKey(comment1.getArticleId());
        if(postCommentStat==null){
            postCommentStat=new PostCommentStat();
            postCommentStat.setCommentCount(1);
        }else{
            postCommentStat.setCommentCount(1+postCommentStat.getCommentCount());
        }
        postCommentStat.setPostId(comment1.getArticleId());
        postCommentStat.setUpdatedAt(Instant.now());

        PostCommentStat stat = postCommentStatMapper.selectByPrimaryKey(comment1.getArticleId());
        if (stat == null) {
            postCommentStatMapper.insert(postCommentStat);
        } else {
            postCommentStatMapper.updateByPrimaryKey(postCommentStat);
        }
        postMapper.incrementCommentCount(comment1.getArticleId(),1);
        postMapper.incrementViewCount(comment1.getArticleId(),1);
        incrementReplyNumById(comment1.getParentId(), comment.getArticleId());

        return Result.success(comment1);
    }

    @Override
    public Result<?> findById(String id) {
        Comment comment=commentRepository.findById(id).orElse(null);
        if(comment==null){
            return Result.error("没有查询到相关评论");
        }
        return Result.success(comment);
    }


    @Override
    public Result<?> findAll() {
        List<Comment>  list=commentRepository.findAll();
        if(list.isEmpty()){
            return Result.error("没有查询到相关评论");
        }
        return Result.success(list);

    }

    @Transactional
    @Override
    public Result<?> deleteById(String id) {
        //TODO:多表关联的删除
        if(commentRepository.findById(id)==null){
            return Result.error("该评论不存在");
        }
        commentRepository.deleteById(id);
        postMapper.incrementCommentCount(id,-1);
        return Result.success();

    }
    @Override
    public Result<?> findByPostId(String postId){
        List<Comment> list=commentRepository.findByArticleId(postId);
        if(list.isEmpty()){
            return Result.error("该帖子没有评论");
        }
        return Result.success(list);
    }
    @Override
    public PageResult getCommentsByArticleId(String articleId, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
        Page<Comment> commentPage = commentRepository.findByArticleId(articleId, pageable);

        return new PageResult(commentPage.getTotalElements(), commentPage.getContent());
    }
    @Transactional
    @Override
    public Result<?> deleteCommentsByArticleId(String articleId) {
        commentRepository.deleteByArticleId(articleId);
        postCommentStatMapper.deleteByPrimaryKey(articleId);
        postMapper.clearCommentCount(articleId,0);
        return Result.success();
    }

}